import 'dart:convert';
import 'dart:io' as Io;
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_app/commom/Dio.dart';
import 'package:flutter_app/commom/Global.dart';
import 'package:flutter_app/models/findUserProjects.dart';
import 'package:flutter_app/widgets/HYSizeFit.dart';
import 'package:flutter_app/widgets/LoginResultCard.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../main.dart';
import 'RegisterRoute.dart';
import 'package:rounded_loading_button/rounded_loading_button.dart';


class HYHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 初始化HYSizeFit
    HYSizeFit.initialize(context);
    return null;
  }
}

class LoginRoute extends StatefulWidget {
  @override
  _LoginRouteState createState() => _LoginRouteState();
}

class _LoginRouteState extends State<LoginRoute> with TickerProviderStateMixin {
  TextEditingController _unameController = new TextEditingController();
  TextEditingController _pwdController = new TextEditingController();
  bool pwdShow = false; //密码是否显示明文
  GlobalKey _formKey = new GlobalKey<FormState>();
  bool _nameAutoFocus = true;
  final file = Io.File('./imgs/企业头像.jpeg');
  final RoundedLoadingButtonController _btnController = new RoundedLoadingButtonController();
  @override
  void initState() {
    //Global.init();
  }
  @override
  Widget build(BuildContext context) {
    HYSizeFit.initialize(context);
    //var gm = GmLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          //mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Column(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(top:100,left: 16,right:16,bottom: 50),
                  child: Column(
                    children: <Widget>[
                      Text("企业帮",
                          //textScaleFactor: 3,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: Colors.grey[700],
                            fontSize: 50,
                            height: 1.2,
                            //fontFamily: "Microsoft YaHei UI",
                            //decorationThickness: 1.0,
                            fontWeight: FontWeight.w900,
                          )),
                    ],
                  ),
                ),
              ],
            ),
            Theme(
                data:new ThemeData(
                  primaryColor: Colors.black,
                ),
                child:Form(
                  key: _formKey,
                  autovalidate: true,
                  child: Column(
                    children: <Widget>[
                      TextFormField(
                          autofocus: _nameAutoFocus,
                          controller: _unameController,
                          decoration: InputDecoration(
                            labelText: '账号',
                            hintText: '账号',
                            prefixIcon: Icon(Icons.person),
                          ),
                          // 校验用户名（不能为空）
                          validator: (v) {
                            return v.trim().isNotEmpty ? null : '请输入您的账号';
                          }),
                      Padding(
                        padding: EdgeInsets.only(top: 10),
                      ),
                      TextFormField(
                        controller: _pwdController,
                        autofocus: !_nameAutoFocus,
                        decoration: InputDecoration(
                            labelText: '密码',
                            hintText: '密码',
                            prefixIcon: Icon(Icons.lock),
                            suffixIcon: IconButton(
                              icon: Icon(
                                  pwdShow ? Icons.visibility_off : Icons.visibility

                              ),
                              onPressed: () {
                                setState(() {
                                  pwdShow = !pwdShow;
                                });
                              },
                            )),
                        obscureText: !pwdShow,
                        //校验密码（不能为空）
                        validator: (v) {
                          return v.trim().isNotEmpty ? null : '请输入密码';
                        },
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top:30.0),
                        child: new GestureDetector(
                          onTap: (){
                            _onLogin();
                          },
                          child: Container(
                            width: HYSizeFit.setPx(550),
                            height: HYSizeFit.setPx(50),
                            alignment: FractionalOffset.center,
                            decoration: new BoxDecoration(
                              color: const Color.fromRGBO(91,100,119,0.7),
                              borderRadius: new BorderRadius.all(const Radius.circular(10.0)),
                            ),
                            child: new Text(
                              "登录",
                              style: new TextStyle(
                                color: Colors.white,
                                fontSize: 20.0,
                                fontWeight: FontWeight.w300,
                                letterSpacing: 50,
                              ),
                            ),
                          ),
                        )
                        ),
                      Padding(
                        padding: const EdgeInsets.only(top:16.0,left: 20,right:20),
                        child: ConstrainedBox(
                          constraints: BoxConstraints(
                              minWidth: double.infinity, //宽度尽可能大
                              minHeight: 50 //最小高度为50像素
                          ),
                          child: Container(
                            child: Align(
                              alignment: Alignment.bottomCenter,
                              child: FlatButton(
                                child:Text('尚未注册',style: TextStyle(
                                    color: Colors.grey
                                ),
                                ),
                                onPressed: ()=>(
                                    Navigator.push(
                                      context,
                                      new MaterialPageRoute(
                                          builder: (context){
                                            return new RegisterRoute();
                                          }),
                                    )
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
            )
          ],
        )
      ),
      resizeToAvoidBottomPadding: false,
    );
  }
  void _onLogin() async {
    // 提交前，先验证各个表单字段是否合法
    if ((_formKey.currentState as FormState).validate()) {
      showLoading(context);
      try {
        Global.login = await EA(context).login(int.parse(_unameController.text), _pwdController.text);
      } catch (e) {
        //登录失败则提示
        if (e.response?.statusCode == 401) {
          print(e);
          //Navigator.of(context).pop();
        } else{
           //Navigator.of(context).pop();
           //LoginSuccessCard(context);
          Global.login = null;
          print(e);
        }
      } finally {

        // 隐藏loading框
        //Navigator.of(context).pop();
        if (Global.login != null) {
          if(Global.login.status == 200){
            var a = await _dataProcessing();
            if(Global.login.user['usrName'] != '' && Global.login.user['usrTel'] != '' &&
                Global.login.user['usrAd'] != '' && Global.usrBusiness.business != null){
              if(Global.login.user['usrName'] != null && Global.login.user['usrTel'] != null &&
                  Global.login.user['usrAd'] != null && Global.usrBusiness.business != null)
                Global.UserInfo = true;
            }

            else Global.UserInfo = false;
            print(Global.UserInfo);
            Navigator.of(context).pushAndRemoveUntil(
                new MaterialPageRoute(builder: (context) => new BottomNavigationWidget()
                ), (route) => route == null);
          }
          // 返回
          else {
            Navigator.of(context).pop();
            LoginFailedCard(context);
            //Navigator.of(context).pop();
          }
        }
        else {
          Navigator.of(context).pop();
          LoginErrorCard(context);
        }

      }
    }
  }
  Future<int> _dataProcessing() async {
      //return Global.login.status;
      Global.findFriendApl = await EA(context).findFriendApl();
      Global.findUndertakeApl = await EA(context).findUndertakeApl();
      Global.getFriendList = await EA(context).getFriendList();
      Global.findUserProjects = await EA(context).findUserProjects();
      Global.findUserProcedures = await EA(context).getUndertakeList();
      Global.business = await EA(context).business();
      Global.usrBusiness = await EA(context).usrBusiness();
      Global.matchingFriend = await EA(context).matchingFriend();
      return 1;
  }
  void showLoading(context, [String text]) {
    text = text ?? "Loading...";
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return Center(
            child: Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(3.0),
                  boxShadow: [
                    //阴影
                    BoxShadow(
                      color: Colors.white,
                      //offset: Offset(2.0,2.0),
                      blurRadius: 10.0,
                    )
                  ]),
              padding: EdgeInsets.all(16),
              margin: EdgeInsets.all(16),
              constraints: BoxConstraints(maxHeight: 70, maxWidth: 70),
              child: SpinKitRotatingPlain(
                color: Colors.black45,
              )
            ),
          );
        });
  }

}


